<template>
  <!-- 外协 比价单 -->
  <div
    :class="['PriceComparative', { fullScreen }]"
    v-if="info"
  >
    <div class="g-con">
      <div class="flexec">
        <el-icon
          class="icon"
          @click="fullScreen = !fullScreen"
          ><FullScreen
        /></el-icon>
      </div>
      <div
        v-if="!fullScreen"
        class="head flexec mt-2"
      >
        <!-- <el-button> {{ t('exportPDF') }} </el-button> -->
        <el-button
          v-if="type !== 'detail'"
          type="primary"
          @click="handleSave"
        >
          {{ t('userCenter.b10') }}
        </el-button>
      </div>

      <div class="body mt-2">
        <el-table
          ref="table1"
          :data="tableData"
          style="width: 100%"
          border
          scrollbar-always-on
        >
          <el-table-column
            v-for="item in tableColumn"
            :prop="item.prop"
            :label="item.label"
            :width="item.width"
            align="center"
          >
            <template
              #header
              v-if="item.isDel"
            >
              {{ item.label }}
              <el-icon
                @click="handleDel(item.id)"
                class="ml-1 delete-icon"
                ><CircleCloseFilled
              /></el-icon>
            </template>
          </el-table-column>
        </el-table>

        <!--  -->
        <div
          style="height: 700px"
          class="mt-2"
        >
          <el-auto-resizer>
            <template #default="{ height, width }">
              <el-table-v2
                ref="table2"
                :columns="tableColumn4"
                :data="tableData4"
                :width="width"
                :height="height"
                fixed
                scrollbar-always-on
                @scroll="scroll"
              >
                <template #row="props">
                  <Row v-bind="props" />
                </template>
              </el-table-v2>
            </template>
          </el-auto-resizer>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onBeforeMount, cloneVNode, onMounted, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { assistQuoteCompareApi } from '@/service/externalAssistance'
import { insertShcwComparePriceApi, selectShcwComparePriceByIdApi } from '@/service/common'
import { dateFormat, amountFormat, getRandomColor } from '@/utils'
import { useI18n } from 'vue-i18n'
import useDict from '@/hooks/useDict'
const { dictData, getDictData, getDictLabel } = useDict()
import Decimal from 'decimal.js'

const router = useRouter()
const route = useRoute()
const { t, locale } = useI18n()

const activeName = route.query.activeName
const checkedList = ref(route.query?.checkedList?.split(','))
const orderObjApi = 'shcw_assist_order'
const orderId = ref(null)
const projectLargeName = ref('')
const projectLargeId = ref(null)
const type = ref(route.query.type)
const id = route.query.id

onBeforeMount(() => {
  init()
})

const fullScreen = ref(false)
watch(fullScreen, (n) => {
  document.body.style.overflow = n ? 'hidden' : ''
})

//
const table1 = ref(null)
const table2 = ref(null)
onMounted(() => {
  syncScroll()
})
const findTableBody = (dom) => {
  let a, b, c
  a = dom.$refs.bodyWrapper
  b = a.querySelector('.el-scrollbar')
  c = b.querySelector('.el-scrollbar__wrap')
  return c
}
const syncScroll = () => {
  nextTick(() => {
    const table1Body = findTableBody(table1.value)

    table1Body.addEventListener('scroll', () => {
      const num = table1Body.scrollLeft
      table2.value.scrollToLeft(num)
    })
  })
}
const scroll = ({ xAxisScrollDir, scrollLeft, yAxisScrollDir, scrollTop }) => {
  const table1Body = findTableBody(table1.value)
  table1Body.scrollLeft = scrollLeft
}

const tableColumn = ref([])
const tableData = ref([])

const tableColumn4 = ref([])
const tableData4 = ref([])
const mapListLen = ref(0)

const quoteOrderCurrency = ref('')

// 获取数据
const info = ref({})
const getData = () => {
  assistQuoteCompareApi({
    idList: checkedList.value,
    orderObjApi
  }).then(({ data }) => {
    info.value = data

    const {
      baseQuotaInfo,
      assistQuoteCompareDetailVo: { mapList, shcwAssistOrderDetails }
    } = data

    // 报价说明
    const col1 = []
    const tdata = [
      {
        'prop-0': t('userCenter.t15')
      }
    ]
    baseQuotaInfo.forEach((item, index) => {
      let obj = {}
      if (index === 0) {
        obj = {
          label: item.assistOrderName,
          prop: `prop-${index}`,
          width: 700
        }
        orderId.value = item.id
        quoteOrderCurrency.value = item.quoteOrderCurrency
        projectLargeId.value = item.projectLargeId
        tdata.push({
          'prop-0': item.assistStatement
        })
      } else {
        obj = {
          label: item.enterpriseName,
          prop: `prop-${index}`,
          width: checkedList.value.length >= 2 ? 280 : 560,
          isDel: baseQuotaInfo.length > 2 && type.value !== 'detail',
          id: item.id
        }

        tdata.forEach((d, i) => {
          if (i === 0) {
            d[`prop-${index}`] = t('userCenter.t14')
          } else {
            d[`prop-${index}`] = item.quotationDescription
          }
        })
      }
      col1.push(obj)
    })
    tableColumn.value = col1
    tableData.value = tdata

    // 外协明细
    getCol4Data()
    mapList.forEach((item, index) => {
      const colum = [
        {
          title: t('userCenter.price'), //
          key: `prop-0-${index}`,
          dataKey: `prop-0-${index}`,
          width: checkedList.value.length >= 2 ? 280 / 4 : 280 / 2,
          align: 'center',
          cellRenderer: ({ rowData, rowIndex }) => {
            return rowIndex !== tableData4.value.length - 1 ? amountFormat(rowData[`prop-0-${index}`]) : rowData[`prop-0-${index}`]
          }
        },
        {
          title: t('userCenter.discount'), //
          key: `prop-1-${index}`,
          dataKey: `prop-1-${index}`,
          width: checkedList.value.length >= 2 ? 280 / 4 : 280 / 2,
          align: 'center'
        },
        {
          title: t('userCenter.t12'),
          key: `prop-2-${index}`,
          dataKey: `prop-2-${index}`,
          width: checkedList.value.length >= 2 ? 280 / 4 : 280 / 2,
          align: 'center',
          // fixed: 'right'
          cellRenderer: ({ rowData, rowIndex }) => {
            return amountFormat(rowData[`prop-2-${index}`])
          }
        },
        {
          title: t('userCenter.remark'), //
          key: `prop-3-${index}`,
          dataKey: `prop-3-${index}`,
          width: checkedList.value.length >= 2 ? 280 / 4 : 280 / 2,
          align: 'center'
          // fixed: 'right'
        }
      ]
      tableColumn4.value = [...tableColumn4.value, ...colum]
    })

    shcwAssistOrderDetails.forEach((item, index) => {
      mapList.forEach((m, i) => {
        item[`prop-0-${i}`] = m[item.id].price
        item[`prop-1-${i}`] = m[item.id].discount
        item[`prop-2-${i}`] = m[item.id].amount
        item[`prop-3-${i}`] = m[item.id].quotaRemark
      })
    })

    const lastObj = {}
    mapList.forEach((m, i) => {
      let total = Decimal(0)
      shcwAssistOrderDetails.forEach((item) => {
        total = total.add(Decimal(item[`prop-2-${i}`] || 0))
      })
      lastObj[`prop-0-${i}`] = `${t('userCenter.total')}: ${amountFormat(Number(total))} ${dictData.value['currency']?.find((item) => item.dictValue === quoteOrderCurrency.value)?.dictLabel}`
    })
    shcwAssistOrderDetails.push(lastObj)

    tableData4.value = shcwAssistOrderDetails

    mapListLen.value = mapList.length
  })
}

const colorArr = ref([])

// cell
const Row = ({ rowData, rowIndex, cells, columns }) => {
  // console.log(rowData, rowIndex, cells, columns, '===')

  // 背景色
  let backgroundColor = ''
  for (let index = initColLen.value; index < initColLen.value + mapListLen.value * 4; index++) {
    if (!colorArr.value.some((item) => item.index === index)) {
      colorArr.value.push({
        index,
        color: getRandomColor()
      })
    }

    if ((index - initColLen.value) % 4 === 0) {
      backgroundColor = colorArr.value.find((item) => item.index === index).color
    }

    if (!cells[index]) return
    const style = {
      ...cells[index].props.style,
      backgroundColor
    }

    cells[index] = cloneVNode(cells[index], { style })
  }

  // 比较
  const amountArr = []
  for (let index = 0; index < mapListLen.value; index++) {
    amountArr.push({
      key: `prop-2-${index}`,
      value: rowData[`prop-2-${index}`]
    })
  }

  amountArr.sort((a, b) => {
    return a.value - b.value
  })
  // console.log(amountArr)

  if (amountArr[0].value === null) return cells

  const colSpanIndex = columns.findIndex((item) => item.key === amountArr[0].key)

  const style = {
    ...cells[colSpanIndex].props.style,
    backgroundColor: '#F8CD95'
  }
  cells[colSpanIndex] = cloneVNode(cells[colSpanIndex], { style })

  // 合并列
  if (rowIndex === tableData4.value.length - 1) {
    let colSpanIndex = 0
    for (let index = 0; index <= mapListLen.value; index++) {
      if (!cells[colSpanIndex]) return
      let width = Number.parseInt(cells[colSpanIndex].props.style.width)

      for (let i = 1; i < (index === 0 ? initColLen.value : 4); i++) {
        width += Number.parseInt(cells[colSpanIndex + i].props.style.width)
        cells[colSpanIndex + i] = null
      }

      const style = {
        ...cells[colSpanIndex].props.style,
        width: `${width}px`
      }
      cells[colSpanIndex] = cloneVNode(cells[colSpanIndex], { style })
      colSpanIndex = initColLen.value + 4 * index
    }
  }

  return cells
}

// 删除一个 报价
const handleDel = (id) => {
  checkedList.value = checkedList.value.filter((item) => item != id)
  init()
}

// 保存比价单
const handleSave = () => {
  insertShcwComparePriceApi({
    idList: checkedList.value,
    orderObjApi,
    orderId: orderId.value
  }).then(({ msg }) => {
    ElMessage.success(msg)
  })
}

// 坞修明细表头
const initColLen = ref(0)
const getCol4Data = () => {
  const arr_63 = [
    {
      title: t('externalAssistance.category1Col.t1'),
      key: 'assistName',
      dataKey: 'assistName',
      width: 300
    },
    {
      title: t('externalAssistance.category1Col.tit4'),
      key: 'assistSpec',
      dataKey: 'assistSpec',
      width: 200
    },
    {
      title: t('procurement.col.t3'),
      key: 'unit',
      dataKey: 'unit',
      width: 100
    },
    {
      title: t('procurement.category4Col.tit5'),
      key: 'requireCount',
      dataKey: 'requireCount',
      width: 100
    }
  ]
  const obj = {
    63: arr_63,
    64: arr_63,
    65: [
      {
        title: t('externalAssistance.category3Col.t1'),
        key: 'assistName',
        dataKey: 'assistName',
        width: 500
      },
      {
        title: t('externalAssistance.category3Col.t2'),
        key: 'unit',
        dataKey: 'unit',
        width: 100
      },
      {
        title: t('procurement.category4Col.tit5'),
        key: 'requireCount',
        dataKey: 'requireCount',
        width: 100
      }
    ],
    66: [
      {
        title: t('externalAssistance.category3Col.t1'),
        key: 'assistName',
        dataKey: 'assistName',
        width: 500
      },
      {
        title: t('procurement.col.t3'),
        key: 'unit',
        dataKey: 'unit',
        width: 100
      },
      {
        title: t('procurement.category4Col.tit5'),
        key: 'requireCount',
        dataKey: 'requireCount',
        width: 100
      }
    ]
  }
  tableColumn4.value = obj[projectLargeId.value] || []
  initColLen.value = tableColumn4.value.length
}

// 回显 1idList
const getDetail = async () => {
  await selectShcwComparePriceByIdApi({
    id
  }).then(({ data: { idList } }) => {
    checkedList.value = idList
  })
}

// init
const init = async () => {
  if (type.value === 'detail') {
    await getDetail()
  }
  await getDictData('currency')
  getData()
}
</script>

<style scoped lang="scss">
.PriceComparative {
  background: #f5f5f5;
  padding: 30px 0;
  margin-bottom: -76px;

  &.fullScreen {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    overflow: auto;
    z-index: 99999;
    margin-bottom: 0;
    .g-con {
      width: calc(100% - 20px);
    }
  }

  .icon {
    cursor: pointer;
  }

  .el-button {
    min-width: 140px;
  }

  .delete-icon {
    cursor: pointer;
  }

  :deep(.el-table-v2__header-cell) {
    background: #f0f3f8;
    color: #252628;
  }
}
</style>
